package com.wenxixuanwu.fruitstore.controller;

import com.wenxixuanwu.fruitstore.Vo.CommentVo;
import com.wenxixuanwu.fruitstore.entity.Comment;
import com.wenxixuanwu.fruitstore.entity.LogBook;
import com.wenxixuanwu.fruitstore.entity.User;
import com.wenxixuanwu.fruitstore.mapper.CommentMapper;
import com.wenxixuanwu.fruitstore.mapper.LogBookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
public class CommentController {

    @Autowired
    CommentMapper mapper;
    @Autowired
    LogBookMapper looper;

    @RequestMapping("/insert")
    public int addComment(@RequestBody Comment comment, HttpSession session) {
        if (session.getAttribute("u") == null) {
            return 2;
        } else if (comment.getContent() == null) {
            return 3;
        } else if (comment.getUrl().contains(",")) {
            return 4;
        }
        User user = (User) session.getAttribute("u");
        comment.setUserId(user.getId());
        comment.setCreated(new Date());
        mapper.insetComment(comment);
        return 1;
    }

    @RequestMapping("/list")
    public List<CommentVo> selectAll() {

        return mapper.getComment();
    }

    @GetMapping("/quantity")
    public int quantity(HttpSession session, int id) {
        User user = (User) session.getAttribute("u");
        CommentVo cm = mapper.selectById(id);
        if (user != null) {
            LogBook list = looper.selectByUserId(user.getId(), id);
            if (list == null) {
                if (cm.getQuantity() == null) {
                    mapper.setComment(id);
                }
                LogBook logBook = new LogBook();
                logBook.setCommentId(id);
                logBook.setUserId(user.getId());
                looper.insertLogbook(logBook);
                mapper.updateComment(id);
                return 1;
            } else {
                looper.deleteById(user.getId(), id);

                if (cm.getQuantity() == 1) {
                    mapper.setDefaultComment(id);
                } else if (cm.getQuantity()>1) {
                    mapper.reductionComment(id);
                }
                return 2;
            }
        } else {
            return 0;
        }
    }

}
